// #include <chrono>
// #include <iostream>
// #include <opencv2/opencv.hpp>

// #include <windows.h>

// // 截取屏幕指定区域
// cv::Mat CaptureScreen(int x, int y, int w, int h) {
//   HDC hScreenDC = GetDC(NULL);
//   HDC hMemoryDC = CreateCompatibleDC(hScreenDC);
//   HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC, w, h);
//   SelectObject(hMemoryDC, hBitmap);
//   BitBlt(hMemoryDC, 0, 0, w, h, hScreenDC, x, y, SRCCOPY | CAPTUREBLT);

//   BITMAP bitmap;
//   GetObject(hBitmap, sizeof(BITMAP), &bitmap);

//   cv::Mat mat(bitmap.bmHeight, bitmap.bmWidth, CV_8UC4, bitmap.bmBits);
//   cv::cvtColor(mat, mat, cv::COLOR_BGRA2BGR);
//   cv::flip(mat, mat, 0); // 翻转图像行顺序

//   DeleteObject(hBitmap);
//   DeleteDC(hMemoryDC);
//   ReleaseDC(NULL, hScreenDC);

//   return mat.clone();
// }

// bool FindImage(const char *targetPath, int searchX, int searchY, int searchW,
//                int searchH, int *x, int *y) {

//   // 截取屏幕区域
//   cv::Mat screenMat = CaptureScreen(searchX, searchY, searchW, searchH);
//   if (screenMat.empty())
//     return false;

//   // 读取目标图像
//   cv::Mat templateMat = cv::imread(targetPath, cv::IMREAD_COLOR);
//   if (templateMat.empty())
//     return false;

//   // 检查模板尺寸
//   if (templateMat.cols > screenMat.cols || templateMat.rows > screenMat.rows)
//     return false;

//   // 转换为灰度图
//   cv::Mat screenGray, templateGray;
//   cv::cvtColor(screenMat, screenGray, cv::COLOR_BGR2GRAY);
//   cv::cvtColor(templateMat, templateGray, cv::COLOR_BGR2GRAY);

//   // 模板匹配
//   cv::Mat result;
//   cv::matchTemplate(screenGray, templateGray, result, cv::TM_CCOEFF_NORMED);

//   double minVal, maxVal;
//   cv::Point minLoc, maxLoc;
//   cv::minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);

//   const double threshold = 0.8;
//   if (maxVal >= threshold) {
//     *x = searchX + maxLoc.x;
//     *y = searchY + maxLoc.y;
//     return true;
//   }
//   return false;
// }

#include <Windows.h>
#include <chrono>
#include <opencv2/opencv.hpp>
#include <vector>

using namespace cv;

int FindImage(const char *templatePath,
              int searchX,
              int searchY,
              int searchWidth,
              int searchHeight,
              int *outX,
              int *outY)
{
    if (searchWidth <= 0 || searchHeight <= 0)
    {
        return 0;
    }

    // 截取屏幕区域
    HWND hDesktop   = GetDesktopWindow();
    HDC hdc         = GetDC(hDesktop);
    HDC hCaptureDC  = CreateCompatibleDC(hdc);
    HBITMAP hBitmap = CreateCompatibleBitmap(hdc, searchWidth, searchHeight);
    HGDIOBJ hOld    = SelectObject(hCaptureDC, hBitmap);
    BitBlt(hCaptureDC, 0, 0, searchWidth, searchHeight, hdc, searchX, searchY, SRCCOPY);
    SelectObject(hCaptureDC, hOld);
    ReleaseDC(hDesktop, hdc);

    // 获取位图数据
    BITMAPINFOHEADER bi = {0};
    bi.biSize           = sizeof(BITMAPINFOHEADER);
    bi.biWidth          = searchWidth;
    bi.biHeight         = -searchHeight;  // 从上到下
    bi.biPlanes         = 1;
    bi.biBitCount       = 24;
    bi.biCompression    = BI_RGB;

    DWORD bytesPerRow = ((searchWidth * 3 + 3) / 4) * 4;
    std::vector<BYTE> buffer(bytesPerRow * searchHeight);

    if (GetDIBits(hCaptureDC, hBitmap, 0, searchHeight, buffer.data(), (BITMAPINFO *)&bi, DIB_RGB_COLORS) == 0)
    {
        DeleteDC(hCaptureDC);
        DeleteObject(hBitmap);
        return 0;
    }

    // 复制数据到OpenCV Mat，跳过填充字节
    cv::Mat screenMat(searchHeight, searchWidth, CV_8UC3);
    for (int y = 0; y < searchHeight; ++y)
    {
        BYTE *src = buffer.data() + y * bytesPerRow;
        BYTE *dst = screenMat.ptr(y);
        memcpy(dst, src, searchWidth * 3);
    }

    DeleteDC(hCaptureDC);
    DeleteObject(hBitmap);

    // 转换颜色空间 RGB -> BGR
    cv::Mat screenBGR;
    cvtColor(screenMat, screenBGR, COLOR_RGB2BGR);

    // 读取模板图像
    cv::Mat templateImg = imread(templatePath, IMREAD_COLOR);
    if (templateImg.empty())
    {
        return 0;
    }

    if (templateImg.cols > screenBGR.cols || templateImg.rows > screenBGR.rows)
    {
        return 0;
    }

    // 模板匹配
    cv::Mat result;
    matchTemplate(screenBGR, templateImg, result, TM_CCOEFF_NORMED);

    double maxVal;
    Point maxLoc;
    minMaxLoc(result, nullptr, &maxVal, nullptr, &maxLoc);

    if (maxVal < 0.8)
    {  // 阈值可根据需要调整
        return 0;
    }

    // 计算屏幕坐标
    int posX = maxLoc.x + searchX;
    int posY = maxLoc.y + searchY;

    if (outX)
        *outX = posX;
    if (outY)
        *outY = posY;

    return 1;
}

int main()
{
    int x, y;
    // 获取开始时间点
    auto start = std::chrono::high_resolution_clock::now();

    auto result = FindImage("11.png", 0, 0, 1920, 1080, &x, &y);
    // 获取结束时间点
    auto end = std::chrono::high_resolution_clock::now();

    // 计算耗时（毫秒）
    auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);

    // 输出结果
    std::cout << "函数执行时间为: " << duration_ms.count() << " 毫秒" << std::endl;

    // 打印结果
    if (result)
    {
        std::cout << "Image found at (" << x << ", " << y << ")" << std::endl;
    }
    else
    {
        std::cout << "Image not found" << std::endl;
    }

    return 0;
}